package repository

import (
	"fmt"
	"net/url"
	"strconv"
)

type SearchRequest struct {
	From int
	Size int
}

func (s *SearchRequest) EnsureDefaults() {
	if s.From <= 0 {
		s.From = 0
	}
	if s.Size <= 0 {
		s.Size = 10
	}
}

func (s *SearchRequest) FromQuery(q *url.URL) error {
	from := q.Query().Get("from")
	if from == "" {
		from = q.Query().Get("form")
	}
	size := q.Query().Get("size")
	if from != "" {
		if val, err := strconv.ParseInt(from, 10, 32); err != nil {
			return fmt.Errorf("invalid from format %v", err)
		} else if val < 0 {
			return fmt.Errorf("invalid from")
		} else {
			s.From = int(val)
		}
	}
	if size != "" {
		if val, err := strconv.ParseInt(size, 10, 32); err != nil {
			return fmt.Errorf("invalid size format %v", err)
		} else if val <= 0 {
			return fmt.Errorf("invalid size")
		} else {
			s.Size = int(val)
		}
	}
	return nil
}
